﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using MySql.Data;
using MySql.Data.MySqlClient;
using MySql.Web;


namespace Artemis
{
    // EVE市场中心代码
   
    public partial class EveCentral : Form
    {
        public string typeID;
        public string typeName1;
        public Boolean switchdb = false;
        public EveCentral(string param,Boolean Switch)
        {
            switchdb = Switch;
            typeName1 = param;
            if (Switch == true)
            {
                connectionstring = ConfigurationManager.ConnectionStrings["BackupDataBase"].ConnectionString.ToString();
            }
            else
            {
                connectionstring = ConfigurationManager.ConnectionStrings["MainDataBase"].ConnectionString.ToString();
            }
            InitializeComponent();
        }
        public static string getsell(string typeName, string connectionstring)
        {
           
            string typeID = null;
            try
            {
                typeID = IDGET(typeName, connectionstring);
            }
            catch (MySqlException s)
            {
                MessageBox.Show("SQL ERROR" + s);
            }
            finally
            {
                if (typeID == "No such item")
                {

                }
                else
                {
                    string url = null;
                    url = "http://www.ceve-market.org/api/market/region/10000002/system/30000142/type/" + typeID + ".json";   //国服市场中心API的URL
                    string JSON = null;
                    JSON = JSONGET(url);
                    JObject price = JObject.Parse(JSON);
                    JObject sell = (JObject)price["sell"];
                    typeID = (string)sell["min"]; //JSON转化
                }
            }
            return typeID;
                
        }
        public static string getbuy(string typeName, string connectionstring)
        {
            string typeID = null;
            try
            {
                typeID = IDGET(typeName, connectionstring);
            }
            catch (MySqlException s)
            {
                MessageBox.Show("SQL ERROR" + s);
            }
            finally
            {
                if (typeID == "No such item")
                {

                }
                else
                {
                    string url = null;
                    url = "http://www.ceve-market.org/api/market/region/10000002/system/30000142/type/" + typeID + ".json";   //国服市场中心API的URL
                    string JSON = null;
                    JSON = JSONGET(url);
                    JObject price = JObject.Parse(JSON);
                    JObject buy = (JObject)price["buy"];
                    typeID = (string)buy["min"]; //JSON转化
                }
            }
            return typeID;
        }
        public static string JSONGET(string url)//获取指定URL的数据
        {
            try
            {
                WebRequest API = WebRequest.Create(url); //创建对指定URL的WebRequest对象
                HttpWebResponse RSP = (HttpWebResponse)API.GetResponse();//获取响应
                Stream DATA = RSP.GetResponseStream();//创建流DATA，来自响应
                StreamReader rdr = new StreamReader(DATA);//创建读取rdr，读取流DATA数据
                string JSON = rdr.ReadToEnd();
                return JSON;
            }
            catch (WebException e)
            {
                MessageBox.Show("网络异常"+e);
                return "{\"sell\":{\"volume\":0,\"max\":0,\"min\":0},\"all\":{\"volume\":0,\"max\":0,\"min\":0},\"buy\":{\"volume\":0,\"max\":0,\"min\":0}}";
            }
           
        }
        public static string IDGET(string typeName,string connectionstring)//从远程数据库获得指定typeName物品的typeID
        {

            DataSet id = new DataSet();
            MySqlConnection conn = null;
            conn = new MySqlConnection();
            conn.ConnectionString = connectionstring;
            string sql = "SELECT typeID FROM eve_main.invtypes WHERE typeName=@typeName;";
            conn.Open();
            MySqlCommand commd = new MySqlCommand("set names utf8", conn);
            commd.ExecuteNonQuery();
            commd.Dispose();
            MySqlCommand query = new MySqlCommand(sql, conn);
            query.Parameters.Add(new MySqlParameter("@typeName", typeName));
            MySqlDataAdapter mda = new MySqlDataAdapter(query);
            mda.Fill(id, "ItemID");
            conn.Close();
            if (id != null && id.Tables[0].Rows.Count != 0)
            {
                string typeID = null;
                typeID = id.Tables["ItemID"].Rows[0]["TypeID"].ToString();
                return typeID;
            }
            else
            {
                string typeID = null;
                typeID = "No such item";
                return typeID;
            }
        }
        public static DataSet getdata(MySqlCommand query,string tablename,string connstring)
        {
            DataSet names = new DataSet();
            MySqlConnection conn = null;
            conn = new MySqlConnection();
            conn.ConnectionString = connstring;
            conn.Open();
            query.Connection = conn;
            MySqlDataAdapter mda = new MySqlDataAdapter(query);
            mda.Fill(names, tablename);
            conn.Close();
            return names;
        }    //通用获得数据方法

        public string connectionstring = null;
        private void EveCentral_Load(object sender, EventArgs e)
        {
            connectionstring = ConfigurationManager.ConnectionStrings["MainDataBase"].ConnectionString.ToString();
            if (switchdb == true)
            {
                connectionstring = ConfigurationManager.ConnectionStrings["BackupDataBase"].ConnectionString.ToString();
            }
            else
            {
                connectionstring = ConfigurationManager.ConnectionStrings["MainDataBase"].ConnectionString.ToString();
            }

            if (typeName1 != null)
            {
                string typeName = typeName1;
                comboBox1.Text = typeName;
                string typeID = null;
                string sql = null;
                try
                {
                    typeID = IDGET(typeName,connectionstring);
                }
                catch (MySqlException s)
                {
                    MessageBox.Show("SQL ERROR" + s);
                }
                finally
                {
                    if (typeID == "No such item")
                    {
                        try
                        {
                            sql = "SELECT typeName FROM `invtypes` WHERE typeName LIKE @typeName ORDER BY typeName DESC;";
                            DataSet similarnames = new DataSet();
                            MySqlCommand query = new MySqlCommand(sql);
                            query.Parameters.Add(new MySqlParameter("@typeName", typeName + "%"));
                            similarnames = getdata(query, "Names", connectionstring);
                            if (similarnames != null && similarnames.Tables[0].Rows.Count != 0)
                            {
                                List<object> names = new List<object>();
                                names = Agents.refreshnoemptyline(similarnames, "Names", "typeName");
                                comboBox1.DataSource = names;
                            }
                            else
                            {
                                comboBox1.Text = "该物品不存在";
                            }
                        }
                        catch (MySqlException sqe1)
                        {
                            MessageBox.Show("SQL ERROR" + sqe1);
                        }

                    }
                    else
                    {
                        string url = null;
                        url = "http://www.ceve-market.org/api/market/region/10000002/system/30000142/type/" + typeID + ".json";   //国服市场中心API的URL
                        string JSON = null;
                        JSON = JSONGET(url);
                        JObject price = JObject.Parse(JSON);
                        JObject sell = (JObject)price["sell"];
                        JObject buy = (JObject)price["buy"];
                        string sel = (string)sell["min"];
                        string bu = (string)buy["max"]; //JSON转化
                        if (sel != null & bu != null)
                        {

                            float biu = float.Parse(bu);
                            float sie = float.Parse(sel);
                            string bui = string.Format("{0:0,00.00}", biu);
                            string sei = string.Format("{0:0,00.00}", sie);
                            selllabel.Text = sei + "ISK";
                            buylabel.Text = bui + "ISK";
                        }
                        if (sel == null & bu != null)
                        {
                            float biu = float.Parse(bu);
                            string bui = string.Format("{0:0,00.00}", biu);
                            buylabel.Text = bui + "ISK";
                            selllabel.Text = "无出售订单";
                        }
                        if (sel != null & bu == null)
                        {
                            float sie = float.Parse(sel);
                            string sei = string.Format("{0:0,00.00}", sie);
                            selllabel.Text = sei + "ISK";
                            buylabel.Text = "无购买订单";
                        }
                        if (sel == null & bu == null)
                        {
                            selllabel.Text = "无出售订单";
                            buylabel.Text = "无购买订单";
                        }

                    }
                }
            }   
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string typeName = null;
            if (typeName1 == null)
            {
                typeName = comboBox1.Text;
            }
            string typeID = null;
            string sql = null;
            try
            {
                typeID = IDGET(typeName,connectionstring);
            }
            catch (MySqlException s)
            {
                MessageBox.Show("SQL ERROR" + s);
            }
            finally
            {
                if(typeID=="No such item")
                {
                    try
                    {
                        sql = "SELECT typeName FROM `invtypes` WHERE typeName LIKE @typeName ORDER BY typeName DESC;";
                        DataSet similarnames = new DataSet();
                        MySqlCommand query = new MySqlCommand(sql);
                        query.Parameters.Add(new MySqlParameter("@typeName", typeName + "%"));
                        similarnames = getdata(query, "Names", connectionstring);
                        if (similarnames != null && similarnames.Tables[0].Rows.Count != 0)
                        {
                          List<object> names = new List<object>();
                          names = Agents.refreshnoemptyline(similarnames, "Names", "typeName");
                          comboBox1.DataSource = names;
                        }
                        else
                        {
                          comboBox1.Text = "该物品不存在";
                        }
                    }
                    catch (MySqlException sqe1)
                    {
                        MessageBox.Show("SQL ERROR" + sqe1);
                    }
                    
                }
                else
                {
                    string url = null;
                    url = "http://www.ceve-market.org/api/market/region/10000002/system/30000142/type/" + typeID + ".json";   //国服市场中心API的URL
                    string JSON = null;
                    JSON = JSONGET(url);
                    JObject price = JObject.Parse(JSON);
                    JObject sell = (JObject)price["sell"];
                    JObject buy = (JObject)price["buy"];
                    string sel = (string)sell["min"];
                    string bu = (string)buy["max"]; //JSON转化
                    if (sel != null & bu != null)
                    {

                        float biu = float.Parse(bu);
                        float sie = float.Parse(sel);
                        string bui = string.Format("{0:0,00.00}", biu);
                        string sei = string.Format("{0:0,00.00}", sie);
                        selllabel.Text = sei + "ISK";
                        buylabel.Text = bui + "ISK";
                    }
                    if (sel == null & bu != null)
                    {
                        float biu = float.Parse(bu);
                        string bui = string.Format("{0:0,00.00}", biu);
                        buylabel.Text = bui + "ISK";
                        selllabel.Text = "无出售订单";
                    }
                    if (sel != null & bu == null)
                    {
                        float sie = float.Parse(sel);
                        string sei = string.Format("{0:0,00.00}", sie);
                        selllabel.Text = sei + "ISK";
                        buylabel.Text = "无购买订单";
                    }
                    if (sel == null & bu == null)
                    {
                        selllabel.Text = "无出售订单";
                        buylabel.Text = "无购买订单";
                    }
                        
                }
            }
        }

        private void bindingSource1_CurrentChanged(object sender, EventArgs e)
        {

        }

        private void bindingSource1_CurrentChanged_1(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            button1_Click(sender, e);
        }
      
    }
}
